#include "mainwindow.h"

QList<QString>nameList;

FileRenamer::FileRenamer(QWidget *parent) : QWidget(parent)
{
    setupUI();
    loadFileList();
    load = new LoadingOverlay(this);
    load->hide();
    // 在线程中进行预览操作
    m_thread = new QThread(this);
    PreviewThread *pthread = new PreviewThread;
    connect(this,&FileRenamer::sendFilePath,pthread,&PreviewThread::getFilePathFromMainThread);
    connect(this,&FileRenamer::sendComboboxText,pthread,&PreviewThread::getComboBoxTextFromMainThread);
    connect(this,&FileRenamer::sendLineEditText,pthread,&PreviewThread::getlineEditTextFromMainThread);
    connect(this,&FileRenamer::sendReplacementText,pthread,&PreviewThread::getReplacementTextFromMainThread);
    connect(pthread,&PreviewThread::finishLoop,this,&FileRenamer::updateModelPreview);
    connect(pthread,&PreviewThread::finishLoop,load,&LoadingOverlay::hideOverlay);
    connect(m_thread,&QThread::finished,pthread,&PreviewThread::deleteLater);
    connect(this,&FileRenamer::startPreviewThread,pthread,&PreviewThread::previewThreadRun);
    pthread->moveToThread(m_thread);
    m_thread->start();
}

FileRenamer::~FileRenamer()
{
    m_thread->quit();
    m_thread->wait();
}

void FileRenamer::setupUI()
{
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    // 目录选择
    QHBoxLayout *dirLayout = new QHBoxLayout();
    QLabel *dirLabel = new QLabel("目录:");
    QPushButton *selectBtn = new QPushButton("选择...");
    connect(selectBtn, &QPushButton::clicked, this, &FileRenamer::selectDirectory);
    dirLayout->addWidget(dirLabel);
    dirLayout->addWidget(selectBtn);
    mainLayout->addLayout(dirLayout);

    // 操作选择
    QHBoxLayout *opLayout = new QHBoxLayout();
    operationCombo = new QComboBox();
    operationCombo->addItems({"添加前缀", "添加后缀", "替换文本", "大小写转换"});
    editText = new QLineEdit();
    replacementText = new QLineEdit();
    replacementText->setPlaceholderText("替换为");

    QLabel *opLabel = new QLabel("操作:");
    opLayout->addWidget(opLabel);
    opLayout->addWidget(operationCombo);
    opLayout->addWidget(editText);
    opLayout->addWidget(replacementText);
    mainLayout->addLayout(opLayout);

    // 预览功能
    QPushButton *previewBtn = new QPushButton("预览");
    connect(previewBtn, &QPushButton::clicked, this, &FileRenamer::previewRename);
    // connect(previewBtn, &QPushButton::clicked, this, &FileRenamer::updateModelPreview);
    mainLayout->addWidget(previewBtn);

    // 文件列表视图
    QTableView *tableView = new QTableView();
    model = new QStandardItemModel(0, 3, this);
    model->setHorizontalHeaderLabels({"原文件名", "新文件名", "完整路径"});
    tableView->setModel(model);
    for(int var = 0; var < model->columnCount(); ++var)
    {
        qDebug() << model->columnCount();
        if(var < model->columnCount() - 1)
            tableView->horizontalHeader()->setSectionResizeMode(var,QHeaderView::ResizeToContents);
        else
            tableView->horizontalHeader()->setSectionResizeMode(var,QHeaderView::Stretch);
    }
    mainLayout->addWidget(tableView);

    // 执行按钮
    QPushButton *executeBtn = new QPushButton("执行重命名");
    connect(executeBtn, &QPushButton::clicked, this, &FileRenamer::executeRename);
    mainLayout->addWidget(executeBtn);

    // 隐藏替换文本框（根据操作显示）
    replacementText->setVisible(false);
    connect(operationCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),this,
            [=](int index)
            {
                replacementText->setVisible(index == 2); // 仅在替换文本时显示
            });
}

void FileRenamer::loadFileList()
{
    model->removeRows(0, model->rowCount());
    QDirIterator it(currentDir.absolutePath(), QDir::Files, QDirIterator::Subdirectories);
    while (it.hasNext())
    {
        it.next(); // 迭代器向后移动
        QFileInfo info(it.fileInfo());

        // 跳过隐藏文件（可选）
        if (info.fileName().startsWith('.')) continue;

        QList<QStandardItem*> row;
        row << new QStandardItem(info.fileName());
        row << new QStandardItem(""); // 新文件名
        row << new QStandardItem(info.absoluteFilePath());
        model->appendRow(row);
    }
}

void FileRenamer::selectDirectory()
{
    QString dirPath = QFileDialog::getExistingDirectory(this, "选择目录");
    if (!dirPath.isEmpty())
    {
        currentDir.setPath(dirPath);
        emit sendFilePath(dirPath);
        loadFileList();
    }
}

void FileRenamer::previewRename()
{
    qDebug() << "main:" << this->thread();
    // PreviewThread线程使用主线程数据
    QString operation = operationCombo->currentText();
    QString text = editText->text();
    emit sendComboboxText(operation);
    emit sendLineEditText(text);
    emit sendFilePath(currentDir.absolutePath());
    if(operation == "替换文本")
    {
        emit sendReplacementText(replacementText->text());
    }
    emit startPreviewThread();

    // LoadingOverlay会生成一个转圈动画
    load->showOverlay();
}

void FileRenamer::updateModelPreview()
{
    // 更新预览
    const QList<QString>& list = nameList;
    model->removeRows(0, model->rowCount());
    QDirIterator it_dir(currentDir.absolutePath(), QDir::Files, QDirIterator::Subdirectories);
    QList<QString>::ConstIterator newName = list.constBegin();
    while (it_dir.hasNext())
    {
        it_dir.next(); // 迭代器向后移动
        QFileInfo info(it_dir.fileInfo());

        // 跳过隐藏文件（可选）
        if (info.fileName().startsWith('.')) continue;

        QList<QStandardItem*> row;
        row << new QStandardItem(info.fileName());
        row << new QStandardItem(*newName); // 新文件名
        row << new QStandardItem(info.absolutePath() + "/" + *newName);
        newName++;
        model->appendRow(row);
    }
}

void FileRenamer::executeRename()
{
    bool success = true;
    for (int row = 0; row < model->rowCount(); ++row)
    {
        QString oldName = model->item(row, 0)->text();
        QString newName = model->item(row, 1)->text();

        if (!QFile::rename(currentDir.filePath(oldName),currentDir.filePath(newName)))
        {
            success = false;
            QMessageBox::warning(this, "错误","重命名失败: " + oldName + " -> " + newName);
        }
    }
    if (success)
    {
        QMessageBox::information(this, "完成", "所有文件重命名成功！");
        loadFileList(); // 刷新列表
    }
}

//---------------------------------------Thread-------------------------------------------------
void PreviewThread::previewThreadRun()
{
    nameList.resize(0);
    qDebug() << filePath;
    // 构建重命名规则
    QDirIterator it(filePath, QDir::Files, QDirIterator::Subdirectories);;
    while(it.hasNext())
    {
        it.next(); // 迭代器向后移动
        QFileInfo info(it.fileInfo());
        // 跳过隐藏文件（可选）
        if (info.fileName().startsWith('.'))
            continue;

        QString oldName = info.fileName();
        QString newName = oldName;
        if (comboBoxText == "添加前缀")
        {
            newName = lineEditText + oldName;
        }
        else if (comboBoxText == "添加后缀")
        {
            newName = oldName + lineEditText;
        }
        else if (comboBoxText == "替换文本")
        {
            newName.replace(lineEditText, replacementText);
        }
        else if (comboBoxText == "大小写转换")
        {
            if(oldName.isUpper())
                newName = oldName.toLower();
            else
                newName = oldName.toUpper();
        }
        nameList.append(newName);
    }
    emit finishLoop();
}
